package com.roc.web.action.unPay;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.UnPayStatement;
import com.roc.service.IExcelService;
import com.roc.service.unPay.IUnPayService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
*@auhor   zbl
*@date    2017年4月18日 下午1:06:59
*@desc    说明 直连交易报表导出 
**/
@Controller
@Namespace("/unpayStatement")
public class UnPayStatementAction extends PaginationBaseAction{
	
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(UnPayStatementAction.class);
	
	private UnPayStatementSearchCondition searchCondition;
	private InputStream excelFile;
	
	@Autowired
	private IExcelService excelService;
	
	@Autowired
	private IPageService pagenitionService;
	
	@Autowired
	IUnPayService unPayService;
	
	/**
	 * 初始化直连商户报表导出页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name =SUCCESS, location = "/pages/unPay/unPayStatement.jsp"),
			@Result(name =ERROR, location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())) {
			return SUCCESS;
		}
		
		addActionError("无权限访问!!!");
		return ERROR;    
	} 
	
	
	/**
	 * 查询操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryUnpayStatement", results = {
			@Result(name = "success", location = "/pages/unPay/unPayStatement.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryUnpayStatement() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (UnPayStatementSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new UnPayStatementSearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);
			
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
				
				List<UnPayStatement> list = new ArrayList<UnPayStatement>();
				if(null != searchRsList && searchRsList.size()>0){
					Iterator<?> it = searchRsList.iterator();
					
					while(it.hasNext()){
						Object[] obj = (Object[]) it.next();
						UnPayStatement us = new UnPayStatement();
						
						DecimalFormat df=new DecimalFormat("#.##");//数据库存的分，转成元保留小数点后两位
						
						us.setMerchantNo(Constance.Null2EmptyTrim(obj[0]));
						us.setTerminalNo(Constance.Null2EmptyTrim(obj[1]));
						us.setSerialNo(Constance.Null2EmptyTrim(obj[2]).substring(6));
						us.setBranch(Constance.Null2EmptyTrim(obj[3]));
						us.setSysNo(Constance.Null2EmptyTrim(obj[4]));
						us.setAccount(Constance.Null2EmptyTrim(obj[5]));
						us.setAmt((df.format(Double.parseDouble(Constance.Null2EmptyTrim(obj[6])))).toString());
						us.setTransResult(Constance.Null2EmptyTrim(obj[7]));
						us.setCardType(Constance.Null2EmptyTrim(obj[8]));
						if(null==Constance.Null2EmptyTrim(obj[9]) || "".equals(Constance.Null2EmptyTrim(obj[9]))){
							us.setTransAmt(Constance.Null2EmptyTrim(obj[9]));
						}else{
							us.setTransAmt((df.format(Double.parseDouble(Constance.Null2EmptyTrim(obj[9])))).toString());
						}
						if(null==Constance.Null2EmptyTrim(obj[10]) || "".equals(Constance.Null2EmptyTrim(obj[10]))){
							us.setFee(Constance.Null2EmptyTrim(obj[10]));
						}else{
							us.setFee((df.format(Double.parseDouble(Constance.Null2EmptyTrim(obj[10])))).toString());
						}
						if(null==Constance.Null2EmptyTrim(obj[11]) || "".equals(Constance.Null2EmptyTrim(obj[11]))){
							us.setSettleAmt(Constance.Null2EmptyTrim(obj[11]));
						}else{
							us.setSettleAmt((df.format(Double.parseDouble(Constance.Null2EmptyTrim(obj[11])))).toString());
						}
						us.setTransDate(Constance.Null2EmptyTrim(obj[12]));
						us.setSettleDate(Constance.Null2EmptyTrim(obj[13]));
						us.setIsHandle(Constance.Null2EmptyTrim(obj[14]));
						list.add(us);
					}
					searchRsList.clear();
					searchRsList.addAll(list);
				}
			}
			if (searchRsList.size() == 0) {
				addActionMessage("查询结果为空！");
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
			
		}
		return SUCCESS;
	}
	
	
	/**
	 * 直连商户报表导出
	 * @return
	 * @throws Exception
	 */
	@Action(value = "exportUnpayStatement", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String exportUnpayStatement() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (UnPayStatementSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new UnPayStatementSearchCondition();
				}
			}
			List<UnPayStatement> unlist = new ArrayList<UnPayStatement>();
			
			unlist = unPayService.queryStatement(searchCondition);
			logger.info("开始导出银联直连商户报表！");
			SXSSFWorkbook work = excelService.exportUnpayMcht(unlist);
			
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();
			logger.info("导出银联直连商户报表成功！");
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			
		}
			
		return SUCCESS;
		
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_UNPAY_STATEMENT_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_UNPAY_STATEMENT_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		
		return Constance.PAGE_MAX_SIZE + "";
	}


	public UnPayStatementSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(UnPayStatementSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "银联直联商户交易报表" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}
}
